﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Net.Mail;

namespace StockReportScanner.Engine
{
    public class GetData
    {
        private static Dictionary<String, StockItem> _listSymbol = new Dictionary<string, StockItem>();
        private static Dictionary<String, StockItem> _listStoreSymbol = new Dictionary<string, StockItem>();

        const string MATCH_STRING_SYMBOL = "<a href=\"http://www.cophieu68.vn/snapshot.php?id=";
        const string MATCH_STRING_PRICE = "</span></td>";
        const string ERROR_READ_PRICE = "Error read price";

        public static String HOSE_REPORT_SEARCH_TOKEN = "Qu&#253; 04 Năm 2013";//"Quý 04 Năm 2013";
        const string URL_HOSE_REPORT = "http://www.hsx.vn/hsx/Modules/Danhsach/SymbolDetail.aspx?type=S&MCty={0}";

        const string URL_HASTC_SYMBOL = "http://hnx.vn/web/guest/dang-niem-yet?p_p_id=hsnydkgdjson_WAR_HnxIndexportlet&p_p_lifecycle=0&p_p_state=exclusive&p_p_mode=view&_hsnydkgdjson_WAR_HnxIndexportlet_anchor=toMck&mck={0}";

        public static String HASTC_REPORT_SEARCH_TOKEN = "Báo cáo tài chính quý 4/2013";
        const string URL_HASTC_REPORT = "http://hnx.vn/web/guest/tong-quan?p_p_id=hstongquan_WAR_HnxIndexportlet&p_p_lifecycle=1&p_p_state=exclusive&p_p_mode=view&p_p_col_id=column-9&p_p_col_count=1&_hstongquan_WAR_HnxIndexportlet_anchor=optionSelected&maCk={0}";

        public static String HOSE_URL = @"http://www.cophieu68.vn/stockonline.php?stcid=1";
        public static String HASTC_URL = @"http://www.cophieu68.vn/stockonline.php?stcid=2";

        public static float ParsePrice(String priceStr)
        {
            float price = float.Parse(priceStr, System.Globalization.NumberStyles.Float);
            return price;
        }

        public static Dictionary<String, StockItem> ListSymbol
        {
            get
            {
                return _listSymbol;
            }
        }

        public static void LoadStockList(StockType stockType)
        {
            WebClient client = new WebClient();

            byte[] buffer = null;

            if (stockType == StockType.HOSE)
                buffer = client.DownloadData(HOSE_URL);
            else if (stockType == StockType.HASTC)
                buffer = client.DownloadData(HASTC_URL);

            MemoryStream data = new MemoryStream(buffer);

            StreamReader sr = new StreamReader(data);

            string tempStr = string.Empty;
            string rowMatch = string.Empty;
            string trimStr = string.Empty;

            float price = 0;

            while ((tempStr = sr.ReadLine()) != null)
            {
                trimStr = tempStr.Trim();
                int findIndex = trimStr.IndexOf(MATCH_STRING_SYMBOL);
                if (findIndex > -1)
                {
                    int index0 = findIndex + MATCH_STRING_SYMBOL.Length;
                    int index1 = 0;

                    for (int i = index0; i < trimStr.Length; i++)
                    {
                        if (trimStr[i] == '"')
                        {
                            index1 = i;
                            break;
                        }
                    }

                    String symbol = trimStr.Substring(index0, index1 - index0).ToUpper();

                    //Check valid symbol
                    if (symbol.Length != 3)
                        continue;

                    for (int i = 0; i < 7; i++)
                    {
                        tempStr = sr.ReadLine();
                    }
                    //Ma bi huy niem yet
                    int checkHuyNiemYet = 0;
                    String priceThamChieu = String.Empty;
                    for (int i = 0; i < 3; i++)
                    {
                        tempStr = sr.ReadLine();
                        trimStr = tempStr.Trim();
                        index1 = trimStr.IndexOf(MATCH_STRING_PRICE);
                        if (index1 == -1)
                        {
                            throw new Exception(ERROR_READ_PRICE);
                        }

                        for (int j = index1; j > 0; j--)
                        {
                            if (trimStr[j] == '>')
                            {
                                index0 = j;
                                break;
                            }
                        }

                        String giaThamChieu = trimStr.Substring(index0 + 1, index1 - index0 - 1);
                        if (giaThamChieu == string.Empty)
                            giaThamChieu = "0";

                        price = ParsePrice(giaThamChieu);

                        priceThamChieu = giaThamChieu;
                        checkHuyNiemYet += (int)price;
                    }

                    if (checkHuyNiemYet == 0)
                        continue;

                    StockItem item = new StockItem(symbol, stockType);
                    _listSymbol.Add(symbol, item);
                }
            }
        }

        public static bool SearchReport(String symbol, StockType stockType)
        {
            WebClient client = new WebClient();

            String webContent = null;
            bool bMatch = false;
            if (stockType == StockType.HOSE)
            {
                String url = String.Format(URL_HOSE_REPORT, symbol.ToUpper());
                client.Encoding = Encoding.UTF8;
                webContent = client.DownloadString(url);

                bMatch = webContent.Contains(HOSE_REPORT_SEARCH_TOKEN);
                
            }
            else if (stockType == StockType.HASTC)
            {
                String url = String.Format(URL_HASTC_REPORT, symbol.ToUpper());
                client.Encoding = Encoding.UTF8;
                webContent = client.DownloadString(url);

                bMatch = webContent.Contains(HASTC_REPORT_SEARCH_TOKEN);
            }

            return bMatch;         
        }

        public static void LoadConfigSearch(String fileName)
        {
            string[] lines = System.IO.File.ReadAllLines(fileName);

            foreach (string line in lines)
            {
                String[] tokens = line.Split(':');
                if (String.Compare(tokens[0], "Hose", true) == 0)
                    HOSE_REPORT_SEARCH_TOKEN = tokens[1];
                else if (String.Compare(tokens[0], "Hastc", true) == 0)
                    HASTC_REPORT_SEARCH_TOKEN = tokens[1];
            }
        }

        public static void LoadUrlConfig(String fileName)
        {
            try
            {
                string[] lines = System.IO.File.ReadAllLines(fileName);
                HOSE_URL = lines[0];
                HASTC_URL = lines[1];
            }
            catch
            {

            }
        }

        public static Dictionary<String, StockItem> ListStoreSymbol
        {
            get
            {
                return _listStoreSymbol;
            }
        }

        public static void LoadStoreSymbol(string fileName)
        {
            _listStoreSymbol.Clear();
            try
            {

                string[] lines = System.IO.File.ReadAllLines(fileName);

                foreach (string line in lines)
                {
                    StockItem item = null;
                    String[] tokens = line.Split(',');
                    if (String.Compare(tokens[0], "Hose", true) == 0)
                        item = new StockItem(tokens[1].ToUpper(), StockType.HOSE);
                    else if (String.Compare(tokens[0], "Hastc", true) == 0)
                        item = new StockItem(tokens[1].ToUpper(), StockType.HASTC);

                    if (String.Compare(tokens[2], "True", true) == 0)
                        item.HasReport = true;
                    else
                        item.HasReport = false;

                    _listStoreSymbol.Add(item.Symbol, item);
                }
            }
            catch
            {

            }

        }

        public static void SaveStoreSymbol(string fileName)
        {
            string[] lines = new string[_listStoreSymbol.Count];
            int count = 0;
            foreach (StockItem stockItem in _listStoreSymbol.Values)
            {
                lines[count] = String.Format("{0},{1},{2}", stockItem.StockType.ToString(), stockItem.Symbol, stockItem.HasReport.ToString());
                count++;
            }
            System.IO.File.WriteAllLines(fileName, lines);
        }

        public static void SaveDictionary(string fileName, Dictionary<String, StockItem> dictSymbol)
        {
            string[] lines = new string[dictSymbol.Count];
            int count = 0;
            foreach (StockItem stockItem in dictSymbol.Values)
            {
                lines[count] = String.Format("{0},{1},{2}", stockItem.StockType.ToString(), stockItem.Symbol, stockItem.HasReport.ToString());
                count++;
            }
            System.IO.File.WriteAllLines(fileName, lines);
        }

        public static void CloneSymbolToStore()
        {
            _listStoreSymbol.Clear();
            foreach (StockItem stockItem in _listSymbol.Values)
            {
                //StockItem item = new StockItem(stockItem.Symbol, stockItem.Symbol);
                //item.HasReport = stockItem.HasReport;
                //_listStoreSymbol.Add(item.Symbol, item);

                _listStoreSymbol.Add(stockItem.Symbol, stockItem);
            }

        }


        public static void SendMail(String subject, String body)
        {
            try
            {
                var fromAddress = new MailAddress("pbtdanh@gmail.com", "Danh Phan");
                var toAddress = new MailAddress("pbtdanh@yahoo.com", "Danh Phan");
                const string fromPassword = "chaudanh";

                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    smtp.Send(message);
                }
            }
            catch
            {

            }
        }

        public static void SendReport(Dictionary<String, StockItem> dictSymbol)
        {
            if (dictSymbol.Count == 0)
                return;

            StringBuilder sb = new StringBuilder();
            sb.Append("Stock: ");
            foreach (StockItem stockItem in dictSymbol.Values)
            {
                sb.Append(stockItem.Symbol);
                sb.Append(", ");
            }
            
            String msg = sb.ToString();
            SendMail(msg, msg);            
        }

    }
}
